<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="借出单编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入借出单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:form:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:form:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="formList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="借出单编号" align="center" prop="sn"/>
      <el-table-column label="借出时间" align="center" prop="lendTime" width="130">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lendTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="借出人" align="center" prop="lendPerson" />
      <el-table-column label="借出说明" align="center" prop="lendDesc" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">新创建</span>
          <span v-else-if="scope.row.status === 1">已确认</span>
          <span v-else-if="scope.row.status === 2">已归还</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 0 || scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:out:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleConfirm(scope.row)"
            v-if="scope.row.status === 0"
            v-hasPermi="['system:form:confirm']"
          >确认</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleReturn(scope.row)"
            v-if="scope.row.status === 1"
            v-hasPermi="['system:form:return']"
          >归还</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:form:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品借出单(es_lend_form)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入编号" :disabled="form.isAdd" style="width: 100%"/>
        </el-form-item>

        <!-- 部门名称 -->
        <el-form-item label="部门名称" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择部门名称" style="width: 100%">
            <el-option
              v-for="dept in deptOptions"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <!-- 仓库名称 -->
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择仓库名称" style="width: 100%">
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <!-- 借出人 -->
        <el-form-item label="借出人">
          <el-cascader
            v-model="form.lendPersonId"
            :options="personList"
            :props="{
    checkStrictly: true,
    value: 'id',
    label: 'realName',
    emitPath: false
  }"
            placeholder="请选择借出人"
            style="width: 100%"
            @change="handleCreatorChange"
          />
        </el-form-item>

        <!-- 借出时间 -->
        <el-form-item label="借出时间" prop="lendTime">
          <el-date-picker
            v-model="form.lendTime"
            type="date"
            placeholder="请选择借出时间"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 借出说明 -->
        <el-form-item label="借出说明" prop="lendDesc">
          <el-input v-model="form.lendDesc" type="textarea" placeholder="请输入内容" style="width: 100%"/>
        </el-form-item>

        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <el-button type="primary" size="mini" @click="openProductDialog">选择商品</el-button>

          <el-table :data="form.productList" border style="width: 100%; margin-top: 10px">
            <el-table-column label="商品编号" prop="productSn" align="center" />
            <el-table-column label="商品名称" prop="productName" align="center" />
            <el-table-column label="规格型号" prop="specification" align="center" />
            <el-table-column label="单位" prop="unit" align="center" />
            <el-table-column label="库存数量" prop="stockNum" align="center" />
            <el-table-column label="借出数量" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.lendNum"
                  :min="1"
                  :max="scope.row.stockNum"
                  size="mini"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="removeProduct(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <!-- Product selection dialog -->
      <el-dialog
        title="选择商品"
        :visible.sync="productDialogVisible"
        width="80%"
        append-to-body
      >
        <el-form :inline="true" :model="productQueryParams" size="small">
          <el-form-item label="商品名称">
            <el-input v-model="productQueryParams.productName" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="商品编号">
            <el-input v-model="productQueryParams.productSn" placeholder="请输入商品编号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleProductQuery">搜索</el-button>
            <el-button @click="resetProductQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="productList"
          border
          @selection-change="handleProductSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="商品编号" prop="productSn" align="center" />
          <el-table-column label="商品名称" prop="productName" align="center" />
          <el-table-column label="规格型号" prop="specification" align="center" />
          <el-table-column label="单位" prop="unit" align="center" />
          <el-table-column label="库存数量" prop="stockNum" align="center" />
        </el-table>

        <pagination
          v-show="productTotal>0"
          :total="productTotal"
          :page.sync="productQueryParams.pageNum"
          :limit.sync="productQueryParams.pageSize"
          @pagination="getProductList"
        />

        <div slot="footer" class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProductSelection">确定</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listForm,
  getForm,
  delForm,
  addForm,
  updateForm,
  returnForm,
  confirmForm,
  listAvailableProducts
} from '@/api/system/form'
import { listDept } from "@/api/erpsystem/dept";
import { listWarehouse } from "@/api/system/warehouse";
import {
  getCompiler,
} from "@/api/procurementmanagement/plan";

export default {
  name: "Form",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 部门选项
      deptOptions: [],
      // 仓库选项
      warehouseOptions: [],

      productDialogVisible: false,
      productList: [],
      productTotal: 0,
      selectedProducts: [],
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productSn: null,
        warehouseId: null
      },
      // 管理员用户选项
      //制表人
      personList:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品借出单(es_lend_form)表格数据
      formList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        status: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        lendPersonId: null,
        lendPerson: null,
        lendRegisterId: null,
        lendRegister: null,
        lendTime: null,
        lendDesc: null,
        returnPersonId: null,
        returnPerson: null,
        returnRegisterId: null,
        returnRegister: null,
        returnTime: null,
        returnDesc: null,
        confirmTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "blur" }
        ],
        productList: [
          { required: true, message: "请至少选择一个商品", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDeptOptions();
    this.getWarehouseOptions();
    this.getAdminUserOptions();
  },
  methods: {
    openProductDialog() {
      if (!this.form.warehouseId) {
        this.$message.warning('请先选择仓库')
        return
      }
      this.productQueryParams.warehouseId = this.form.warehouseId
      this.getProductList()
      this.productDialogVisible = true
    },

    getProductList() {
      listAvailableProducts(this.productQueryParams).then(response => {
        this.productList = response.rows
        this.productTotal = response.total
      })
    },

    handleProductQuery() {
      this.productQueryParams.pageNum = 1
      this.getProductList()
    },

    resetProductQuery() {
      this.productQueryParams = {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productSn: null,
        warehouseId: this.form.warehouseId
      }
      this.getProductList()
    },

    handleProductSelectionChange(selection) {
      this.selectedProducts = selection
    },

    confirmProductSelection() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning('请至少选择一个商品')
        return
      }

      const existingIds = this.form.productList?.map(p => p.productId) || []
      const newProducts = this.selectedProducts.filter(
        p => !existingIds.includes(p.productId)
      )

      if (newProducts.length === 0) {
        this.$message.warning('所选商品已存在')
        return
      }

      if (!this.form.productList) {
        this.form.productList = []
      }

      newProducts.forEach(product => {
        this.form.productList.push({
          id: null,
          lendId: this.form.id,
          stockSn: product.stockSn,
          productId: product.productId,
          productName: product.productName,
          productSn: product.productSn,
          specification: product.specification,
          unit: product.unit,
          stockNum: product.stockNum,
          lendNum: 1, // Default to 1
          returnNum: 0,
          goodsId: product.goodsId,
          stockBatchId: product.stockBatchId,
          stockBatchSn: product.stockBatchSn
        })
      })

      this.productDialogVisible = false
    },

    removeProduct(index) {
      this.form.productList.splice(index, 1)
    },

    // 确认按钮操作
    handleConfirm(row) {
      this.$modal.confirm('是否确认借出单编号为"' + row.sn + '"的数据项？').then(() => {
        return confirmForm(row.id); // 调用确认 API
      }).then(() => {
        this.getList(); // 刷新列表
        this.$modal.msgSuccess("确认成功");
      }).catch(() => {});
    },

// 归还按钮操作
    handleReturn(row) {
      this.$modal.confirm('是否确认归还借出单编号为"' + row.sn + '"的数据项？').then(() => {
        return returnForm(row.id); // 调用归还 API
      }).then(() => {
        this.getList(); // 刷新列表
        this.$modal.msgSuccess("归还成功");
      }).catch(() => {});
    },
    /** 查询商品借出单(es_lend_form)列表 */
    getList() {
      this.loading = true;
      listForm(this.queryParams).then(response => {
        this.formList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取部门列表 */
    getDeptOptions() {
      listDept().then(response => {
        response.data.forEach(dept => {
          dept.deptName = dept.name;
        });
        this.deptOptions = response.data;
      });
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    /** 获取管理员用户列表 */
    getAdminUserOptions() {
      listErpuser().then(response => {
        console.log(response)
        this.adminUserOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        status: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        lendPersonId: null,
        lendPerson: null,
        lendRegisterId: null,
        lendRegister: null,
        lendTime: null,
        lendDesc: null,
        returnPersonId: null,
        returnPerson: null,
        returnRegisterId: null,
        returnRegister: null,
        returnTime: null,
        returnDesc: null,
        createTime: null,
        confirmTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleCreatorChange(value) {
      if (value) {
        const selectedId = Array.isArray(value) ? value[value.length - 1] : value;
        const selectedPerson = this.personList.find(p => p.id == selectedId);
        if (selectedPerson) {
          this.form.lendPersonId = selectedId;
          this.form.lendPerson = selectedPerson.realName;
        }
      } else {
        this.form.lendPersonId = null;
        this.form.lendPerson = null;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.isAdd = true; // 设置新增标识
      this.form.sn = this.generateRandomSn(); // 生成随机编号（包含前缀）
      this.getCompiler(); // 获取编制人
      this.open = true;
      this.title = "添加商品借出单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getForm(id).then(response => {
        this.form = response.data;
        this.form.isAdd = false;

        // 确保 lendPersonId 是单个值
        if (Array.isArray(this.form.lendPersonId)) {
          this.form.lendPersonId = this.form.lendPersonId[0];
        }

        this.getCompiler();
        this.open = true;
        this.title = "修改商品借出单";
      });
    },
    //获取编制人
    getCompiler() {
      getCompiler().then(response => {
        this.personList = response.data;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.form.productList || this.form.productList.length === 0) {
            this.$message.warning('请至少选择一个商品')
            return
          }

          // 确保选择了借出人
          if (!this.form.lendPersonId) {
            this.$message.warning('请选择借出人')
            return
          }

          // 查找选中的借出人信息
          const selectedPerson = this.personList.find(p => p.id == this.form.lendPersonId)
          if (selectedPerson) {
            this.form.lendPerson = selectedPerson.realName
          }

          if (this.form.id != null) {
            updateForm(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addForm(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleSize() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = size;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品借出单编号为"' + ids + '"的数据项？').then(function () {
        return delForm(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/form/export', {
        ...this.queryParams
      }, `form_${new Date().getTime()}.xlsx`)
    },
    generateRandomSn() {
      const prefix = "JC"; // 随机编号前缀
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      return `${prefix}${year}${month}${day}${randomNum}`; // 拼接前缀和随机编号
    }
  }
};
</script>

<style scoped>
/* 确保所有表单元素宽度一致 */
.el-form-item__content {
  width: 100%;
}

/* 调整输入框和选择器的基本样式 */
.el-input, .el-select, .el-cascader, .el-date-editor {
  width: 100% !important;
}

/* 调整文本域的高度 */
.el-textarea__inner {
  min-height: 80px;
}

/* 调整表单标签的宽度和对齐 */
.el-form-item__label {
  width: 100px;
  text-align: right;
  padding-right: 12px;
}
</style>
